package com.ke.jun.view.widght

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.net.IpSecManager
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.AttributeSet
import android.view.View
import java.lang.Exception
import java.util.*
import kotlin.math.cos
import kotlin.math.sin

/**
 * 自定义个钟表
 */
class ClickView @JvmOverloads constructor(context: Context,attributeSet: AttributeSet?=null,defStyleAttr: Int=0):View(context,attributeSet,defStyleAttr) {
    companion object{
        private const val DEFAULT_WIDTH =200//默认宽度
    }

    private lateinit var mBlackPaint:Paint//黑色画笔
    private lateinit var mRedPaint:Paint//红色画笔
    private lateinit var mBlackPaint2:Paint//黑色画笔2
    private lateinit var mTextPaint:Paint//文字画笔
    private var hour:Int?=null//时
    private var minute:Int?=null//分
    private var second:Int?=null//秒
      //表盘数组
    private val textArray= arrayOf("12","1","2","3","4","5","6","7","8","9","10","11")

    private var refeshthread:Thread?=null
    private val  mHandler =@SuppressLint("HandlerLeak")
        object :Handler(Looper.myLooper()!!){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when(msg.what){
                0 ->invalidate()
            }
        }

    }

    init {
        initPaint()



    }

    private fun initPaint() {
        mBlackPaint= Paint()
        with(mBlackPaint){
            color=Color.BLACK
            strokeWidth=5f
            isAntiAlias=true
            style=Paint.Style.STROKE
        }
        //画表心
        mBlackPaint2=Paint()
        with(mBlackPaint2){
            color=Color.BLACK
            isAntiAlias=true
            style=Paint.Style.FILL
        }

        mRedPaint= Paint()
        with(mRedPaint){
            color=Color.RED
            strokeWidth=5f
            isAntiAlias=true
        }

        //画文字
        mTextPaint= Paint()
        with(mTextPaint){
            color=Color.BLACK
            isAntiAlias=true
            strokeWidth=30f
        }

    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        //获取当前时间
        getCurrentTime()
        //画最外层的圆
        drawOuterCircle(canvas)
        //画刻度
        drawSclec(canvas)

        //画文字
        drawTextTime(canvas)
        //画表针
        drawHand(canvas)
        //画表心
        drawCenter(canvas)
    }

    private fun drawCenter(canvas: Canvas?) {
        canvas?.drawCircle((measuredHeight/2).toFloat(),
            (measuredHeight/2).toFloat(),20f,mBlackPaint2)
    }

    private fun drawHand(canvas: Canvas?) {
        drawSecond(canvas, mRedPaint)
        mBlackPaint.strokeWidth = 10f
        drawMinute(canvas, mBlackPaint)
        mBlackPaint.strokeWidth = 15f
        drawHour(canvas, mBlackPaint)




    }


    /**
     * 绘制时针
     */
    private fun drawHour(canvas: Canvas?, mBlackPaint: Paint) {
        //半径比秒针小一点
        val longR = measuredWidth / 2 - 120
        val shortR = 40
        val startX = (measuredWidth / 2 - shortR * sin(hour!!.times(Math.PI / 6))).toFloat()
        val startY = (measuredWidth / 2 + shortR * cos(hour!!.times(Math.PI / 6))).toFloat()
        val endX = (measuredWidth / 2 + longR * sin(hour!!.times(Math.PI / 6))).toFloat()
        val endY = (measuredWidth / 2 - longR * cos(hour!!.times(Math.PI / 6))).toFloat()
        canvas?.drawLine(startX, startY, endX, endY, mBlackPaint)

    }

    /**
     * 绘制分针
     */

    private fun drawMinute(canvas: Canvas?, mBlackPaint: Paint) {
       //半径比秒针小一点
        val longR = measuredWidth / 2 - 90
        val shortR = 50
        val startX = (measuredWidth / 2 - shortR * sin(minute!!.times(Math.PI / 30))).toFloat()
        val startY = (measuredWidth / 2 + shortR * cos(minute!!.times(Math.PI / 30))).toFloat()
        val endX = (measuredWidth / 2 + longR * sin(minute!!.times(Math.PI / 30))).toFloat()
        val endY = (measuredWidth / 2 - longR * cos(minute!!.times(Math.PI / 30))).toFloat()
        canvas?.drawLine(startX, startY, endX, endY, mBlackPaint)
    }
    /**
     * 绘制秒针
     */
    private fun drawSecond(canvas: Canvas?, mRedPaint: Paint) {
        //秒针长半径 (表针会穿过表心 所以需要根据两个半径计算起始和结束半径)
        val longR = measuredWidth / 2 - 60
        val shortR = 60
        val startX = (measuredWidth / 2 - shortR * Math.sin(second!!.times(Math.PI / 30))).toFloat()
        val startY = (measuredWidth / 2 + shortR * Math.cos(second!!.times(Math.PI / 30))).toFloat()
        val endX = (measuredWidth / 2 + longR * Math.sin(second!!.times(Math.PI / 30))).toFloat()
        val endY = (measuredWidth / 2 - longR * Math.cos(second!!.times(Math.PI / 30))).toFloat()
        canvas?.drawLine(startX, startY, endX, endY, mRedPaint)

    }

    private fun drawTextTime(canvas: Canvas?) {
        val textR = (measuredWidth / 2 - 50).toFloat()//文字构成的圆的半径
        for (i in 0..11) {
            //绘制文字的起始坐标
            val startX = (measuredWidth / 2 + textR * Math.sin(Math.PI / 6 * i) - mTextPaint.measureText(textArray[i]) / 2).toFloat()
            val startY = (measuredHeight / 2 - textR * Math.cos(Math.PI / 6 * i) + mTextPaint.measureText(textArray[i]) / 2).toFloat()
            canvas?.drawText(textArray[i], startX, startY, mTextPaint)
        }

    }

    private fun drawSclec(canvas: Canvas?) {
        var scaleLength: Float?
        canvas?.save()
        //0..59代表[0,59]
        for (i in 0..59) {
            if (i % 5 == 0) {
                //大刻度
                mBlackPaint.strokeWidth = 5f
                scaleLength = 20f
            } else {
                //小刻度
                mBlackPaint.strokeWidth = 3f
                scaleLength = 10f
            }
            canvas?.drawLine(measuredWidth / 2.toFloat(), 5f, measuredWidth / 2.toFloat(), (5 + scaleLength), mBlackPaint)
            canvas?.rotate(360 / 60.toFloat(), measuredWidth / 2.toFloat(), measuredHeight / 2.toFloat())
        }
        //恢复原来状态
        canvas?.restore()


    }

    private fun drawOuterCircle(canvas: Canvas?) {
        mBlackPaint2.strokeWidth=5f
        canvas?.drawCircle((measuredWidth/2).toFloat(), (measuredHeight/2).toFloat(),
            (measuredHeight/2-5).toFloat(),mBlackPaint)


    }

    private fun getCurrentTime() {
        val calendar = Calendar.getInstance()
        hour=calendar.get(Calendar.HOUR)
        minute=calendar.get(Calendar.MINUTE)
        second=calendar.get(Calendar.SECOND)

    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        var widthMode = MeasureSpec.getMode(widthMeasureSpec)
        var widthSize= MeasureSpec.getSize(widthMeasureSpec)
        var heightSize= MeasureSpec.getSize(heightMeasureSpec)
        var heightMode= MeasureSpec.getMode(heightMeasureSpec)

        val result = if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
            DEFAULT_WIDTH
        } else {
            Math.min(widthSize, heightSize)
        }
        setMeasuredDimension(result, result)

    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        refeshthread=Thread(Runnable {
            while (true){
                try {
                    Thread.sleep(1000)
                    mHandler.sendEmptyMessage(0)
                }catch (e:Exception){

                }


            }
        })

        refeshthread?.start()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        mHandler.removeCallbacksAndMessages(null)
        refeshthread?.interrupt()
    }


}